package com.kly.user.appsflyer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.fqgj.log.util.JsonUtil;
import com.google.api.client.util.Lists;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.kly.user.config.NacosValueConfig;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.*;
import com.kly.user.dto.StoreAppsflyerUserMappingReq;
import com.kly.user.dto.StoreReportReq;
import com.kly.user.enums.AppCodeEnum;
import com.kly.user.enums.AppsFlyerEventDefType;
import com.kly.user.enums.EventPushType;
import com.kly.user.enums.TrafficSourceEnum;
import com.kly.user.mapper.UserAppsflyerMappingMapper;
import com.kly.user.service.AppsflyerService;
import com.kly.user.task.enums.TaskStatusEnum;
import com.kly.user.task.enums.TaskTypeEnum;
import com.kly.user.utils.UserSnowflake;
import com.robert.vesta.util.IdUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 推送数据到appsFlyer
 *
 * @author linqu
 */
@Service("appsflyerService")
public class AppsflyerServiceImpl implements AppsflyerService {
    private static Log logger = LogFactory.getLog(AppsflyerServiceImpl.class);

    @NacosValue(value = "${appsflyer.appid}", autoRefreshed = true)
    private String appId;
    @NacosValue(value = "${pp.appsflyer.appid:com.kky.pp}", autoRefreshed = true)
    private String ppId;
    @NacosValue(value = "${appsflyer.auth}", autoRefreshed = true)
    private String auth;
    @NacosValue(value = "${is.prod.env}", autoRefreshed = true)
    private boolean isTestEnv;
    @Resource
    UserAppsflyerReportDao userAppsflyerReportDao;
    @Resource
    UserAppflyersMappingDao userAppflyersMappingDao;
    @Resource
    UserAppsflyerMappingMapper userAppsflyerMappingMapper;
    @Resource
    UserDao userDao;
    @Resource
    UserAppflyersPushLogDao userAppflyersPushLogDao;
    @Resource
    UserTaskDetailDao userTaskDetailDao;

    @Resource
    UserAppsflyerReportDetailDao appsflyerReportDetailDao;
    @Resource
    UserAppsflyerReportDetailDao userAppsflyerReportDetailDao;
    @NacosValue(value = "${push.switch:Registration,Purchase}", autoRefreshed = true)
    private String pushSwitch;
    @NacosValue(value = "${is.review:true}", autoRefreshed = true)
    private boolean isReview;
    @NacosValue(value = "${update.customer.by.adid:false}", autoRefreshed = true)
    private boolean updateCustomerByAdid;
    /**
     * 数据完整标志
     */
    private final static Integer dataComplete = 1;
    /**
     * 数据不完整标志
     */
    private final static Integer dataNoneComplete = 0;

    private final static Integer fromPushApi = 1;
    private final static Integer fromPullApi = 2;

    @Resource
    CustomersDao customersDao;
    @Resource
    CustomersOldDao customersOldDao;
    @Resource
    CustomersUserDao customersUserDao;
    @Resource
    UserAppsflyerFromAppDao userAppsflyerFromAppDao;
    @Resource
    UserAppsflyerFromAppDetailDao userAppsflyerFromAppDetailDao;
    @Resource
    private NacosValueConfig nacosValueConfig;

    /**
     * appsFlyer 报告存储
     */
    @Override
    public Response storeAppsFlyerReport(StoreReportReq storeReportReq) {
        String reportCode = IdUtils.genId() + "";
        UserAppsflyerReportEntity reportEntity = new UserAppsflyerReportEntity();
        reportEntity.setReportTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMATTER));
        reportEntity.setReportContent(storeReportReq.getReportContent());
        reportEntity.setReportCode(reportCode);
        reportEntity.setDataFrom(fromPushApi);
        userAppsflyerReportDao.insert(reportEntity);

        try {
            Any deserialize = JsonIterator.deserialize(storeReportReq.getReportContent());
            String afChannel = deserialize.get("af_channel") == null ? "" : deserialize.get("af_channel").toString();
            if (StringUtils.isEmpty(afChannel)) {
                afChannel = deserialize.get("media_source") == null ? "" : deserialize.get("media_source").toString();
            }
            String afId = deserialize.get("appsflyer_id") == null ? "" : deserialize.get("appsflyer_id").toString();
            String adId= deserialize.get("advertising_id") == null ? "" : deserialize.get("advertising_id").toString();

            UserAppsflyerReportDetailEntity userAppsflyerReportDetailEntity = new UserAppsflyerReportDetailEntity();
            userAppsflyerReportDetailEntity.setReportCode(reportCode);
            userAppsflyerReportDetailEntity.setAppsflyerId(afId);
            userAppsflyerReportDetailEntity.setEventSource(deserialize.get("event_source") == null ? "" : deserialize.get("event_source").toString());
            userAppsflyerReportDetailEntity.setAppVersion(deserialize.get("app_version") == null ? "" : deserialize.get("app_version").toString());
            userAppsflyerReportDetailEntity.setDeviceModel(deserialize.get("device_model") == null ? "" : deserialize.get("device_model").toString());
            userAppsflyerReportDetailEntity.setAppName(deserialize.get("app_name") == null ? "" : deserialize.get("app_name").toString());
            userAppsflyerReportDetailEntity.setWifi(deserialize.get("wifi") == null ? "" : deserialize.get("wifi").toString());
            userAppsflyerReportDetailEntity.setConversionType(deserialize.get("conversion_type") == null ? "" : deserialize.get("conversion_type").toString());
            userAppsflyerReportDetailEntity.setMediaSource(deserialize.get("media_source") == null ? "" : deserialize.get("media_source").toString());
            userAppsflyerReportDetailEntity.setCampaign(deserialize.get("campaign") == null ? "" : deserialize.get("campaign").toString());
            userAppsflyerReportDetailEntity.setAfChannel(afChannel);
            userAppsflyerReportDetailEntity.setLanguage(deserialize.get("language") == null ? "" : deserialize.get("language").toString());
            userAppsflyerReportDetailEntity.setAdvertisingId(deserialize.get("advertising_id") == null ? "" : deserialize.get("advertising_id").toString());
            userAppsflyerReportDetailEntity.setOsVersion(deserialize.get("os_version") == null ? "" : deserialize.get("os_version").toString());
            userAppsflyerReportDetailEntity.setPlatform(deserialize.get("platform") == null ? "" : deserialize.get("platform").toString());
            userAppsflyerReportDetailEntity.setState(deserialize.get("state") == null ? "" : deserialize.get("state").toString());
            userAppsflyerReportDetailEntity.setCity(deserialize.get("city") == null ? "" : deserialize.get("city").toString());
            appsflyerReportDetailDao.insert(userAppsflyerReportDetailEntity);

            final List<UserEntity> userList = userDao.getUserByAfid(afId);

            for (UserEntity user : userList) {
                final UserAppflyersMappingEntity existsRecordWithNoUserCode = userAppflyersMappingDao.getAppflyerByAfid(userAppsflyerReportDetailEntity.getAppsflyerId());
                if (Objects.nonNull(existsRecordWithNoUserCode) && existsRecordWithNoUserCode.getDataCompleteFlag() == 0) {
                    existsRecordWithNoUserCode.setChannel(afChannel);
                    existsRecordWithNoUserCode.setContent(storeReportReq.getReportContent());
                    existsRecordWithNoUserCode.setCampaign(deserialize.get("af_channel") == null ? "" : deserialize.get("af_channel").toString());
                    existsRecordWithNoUserCode.setAfAdset(deserialize.get("af_adset") == null ? "" : deserialize.get("af_adset").toString());
                    existsRecordWithNoUserCode.setAfAd(deserialize.get("af_ad") == null ? "" : deserialize.get("af_ad").toString());
                    if (StringUtils.isNotEmpty(afChannel)) {
                        existsRecordWithNoUserCode.setDataCompleteFlag(dataComplete);
                    }
                    if (user != null && StringUtils.isEmpty(existsRecordWithNoUserCode.getUserCode())) {
                        existsRecordWithNoUserCode.setUserCode(user.getUserCode());
                    }
                    userAppflyersMappingDao.updateByPrimaryKey(existsRecordWithNoUserCode);
                }

                if (user != null) {
                    if (StringUtils.isEmpty(user.getChannel())) {
                        if (StringUtils.isNotEmpty(afChannel)) {
                            existsRecordWithNoUserCode.setDataCompleteFlag(dataComplete);
                        }
                        user.setChannel(afChannel);
                        userDao.updateByPrimaryKey(user);
                    }

                    // 添加自然人信息
                    Integer trafficType = StringUtils.isNotEmpty(afChannel) ? TrafficSourceEnum.None_Organic.getType() : TrafficSourceEnum.Organic.getType();
                    addCustomer(trafficType, adId, user);
                }

            }





        } catch (Exception e) {
            logger.error("== storeAppsFlyerReport ==",e);
        }
        return Response.ok();
    }

    private void addCustomer(Integer trafficType, String adId, UserEntity user) {
        List<CustomersEntity> customerList = null;
        if (updateCustomerByAdid) {
            // TODO: 2024/6/14 需要处理adid都是0的情况
            customerList = customersDao.listCustomer(user.getMobile(), user.getEmail(), adId);
        } else {
            customerList = customersDao.listCustomer(user.getMobile(), user.getEmail(), null);
        }
        if (CollectionUtils.isEmpty(customerList)) {
            final String customerCode = String.valueOf(UserSnowflake.getInstance().nextId());
            customersDao.addCustomer(customerCode, user.getMobile(), user.getEmail(), adId, trafficType);
            // 添加自然人映射信息
            CustomersUserEntity customersUser = customersUserDao.getCustomer(user.getUserCode());
            if (customersUser == null) {
                customersUserDao.addCustomersUser(customerCode, user.getUserCode());
            }
            return;
        }

        // 更新最近一条自然人信息
        final CustomersEntity customer = customerList.get(0);
        if (StringUtils.isEmpty(customer.getDeviceId())) {
            customer.setDeviceId(adId);
        }
        // 自然流量需要更新
        if (customer.getTrafficType() == null || TrafficSourceEnum.Organic.getType() == customer.getTrafficType()) {
            customer.setTrafficType(trafficType);
        }
        customersDao.updateByPrimaryKey(customer);

        final int customerNum = customerList.size();
        if (customerNum == 1) {
            return;
        }

        // 存在多条自然人信息，取最近一条自然人
        final CustomersEntity latestCustomer = customerList.get(0);
        for (CustomersEntity cus : customerList) {
            if (cus.getCustomerCode().equals(latestCustomer.getCustomerCode())) {
                continue;
            }

            // 归并到最新的自然人记录中
            customersUserDao.moveToNewCustomer(latestCustomer.getCustomerCode(), cus.getCustomerCode());
            // 原来有的自然人在备表里记录，方便追查
            customersOldDao.backUpCustomer(cus);
            // 删除记录
            customersDao.removeByCustomer(cus.getCustomerCode());
        }





    }


    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String utcTime = sdf.format(new Date());

        System.out.println(utcTime);

        System.out.println(DateUtil.now() + ".123");

        String content = "{\"device_category\":\"phone\",\"bundle_id\":\"com.kly.meboo\",\"event_source\":\"SDK\",\"app_version\":\"2.6.3\",\"gp_install_begin\":\"2023-11-15 04:55:24.000\",\"city\":\"Irvington\",\"device_model\":\"motorola::moto g(7) power\",\"gp_referrer\":\"gclid=CjwKCAiA0syqBhBxEiwAeNx9N5g3zUMpoHKUhrtNZ3JNe6tDkblaxqj5ntRXRcNwKZpK5dYRR1_qthoCc6cQAvD_BwE\",\"af_c_id\":\"20737353534\",\"attributed_touch_time_selected_timezone\":\"2023-11-14 20:54:55.474-0800\",\"selected_currency\":\"USD\",\"app_name\":\"Meboo\",\"install_time_selected_timezone\":\"2023-11-14 21:19:18.909-0800\",\"postal_code\":\"07111\",\"wifi\":true,\"install_time\":\"2023-11-15 05:19:18.909\",\"operator\":\"Metro by T-Mobile\",\"attributed_touch_type\":\"click\",\"af_attribution_lookback\":\"7d\",\"campaign_type\":\"ua\",\"af_adset_id\":\"156274840555\",\"device_download_time_selected_timezone\":\"2023-11-14 20:55:33.000-0800\",\"conversion_type\":\"install\",\"api_version\":\"2.0\",\"attributed_touch_time\":\"2023-11-15 04:54:55.474\",\"is_retargeting\":false,\"country_code\":\"US\",\"gp_click_time\":\"2023-11-15 04:55:15.000\",\"match_type\":\"srn\",\"appsflyer_id\":\"1700025555983-705424570639174615\",\"dma\":\"501\",\"media_source\":\"googleadwords_int\",\"campaign\":\"M_GG_2_1104_install_1\",\"region\":\"NA\",\"ip\":\"73.150.151.226\",\"event_time\":\"2023-11-15 05:19:18.909\",\"af_adset\":\"M2_GG_install_1111_4\",\"state\":\"NJ\",\"network_account_id\":2944549368,\"af_channel\":\"ACI_Display\",\"device_download_time\":\"2023-11-15 04:55:33.000\",\"af_reengagement_window\":\"30d\",\"language\":\"English\",\"app_id\":\"com.kly.meboo\",\"af_ad_type\":\"ClickToDownload\",\"event_name\":\"install\",\"advertising_id\":\"e3344c10-908c-4242-99a2-3ed4dc26010d\",\"os_version\":\"10\",\"platform\":\"android\",\"selected_timezone\":\"America/Los_Angeles\",\"user_agent\":\"Dalvik/2.1.0 (Linux; U; Android 10; moto g(7) power Build/QCOS30.85-18-10)\",\"sdk_version\":\"v6.12.1\",\"event_time_selected_timezone\":\"2023-11-14 21:19:18.909-0800\"}";
        Any deserialize = JsonIterator.deserialize(content);
        UserAppsflyerReportDetailEntity userAppsflyerReportDetailEntity = new UserAppsflyerReportDetailEntity();
        userAppsflyerReportDetailEntity.setAppsflyerId(deserialize.get("appsflyer_id").toString());
        userAppsflyerReportDetailEntity.setEventSource(deserialize.get("event_source").toString());
        userAppsflyerReportDetailEntity.setAppVersion(deserialize.get("app_version").toString());
        userAppsflyerReportDetailEntity.setDeviceModel(deserialize.get("device_model").toString());
        userAppsflyerReportDetailEntity.setAppName(deserialize.get("app_name").toString());
        userAppsflyerReportDetailEntity.setWifi(deserialize.get("wifi").toString());
        userAppsflyerReportDetailEntity.setConversionType(deserialize.get("conversion_type").toString());
        userAppsflyerReportDetailEntity.setMediaSource(deserialize.get("media_source").toString());
        userAppsflyerReportDetailEntity.setCampaign(deserialize.get("campaign").toString());
        userAppsflyerReportDetailEntity.setAfChannel(deserialize.get("af_channel").toString());
        userAppsflyerReportDetailEntity.setLanguage(deserialize.get("language").toString());
        userAppsflyerReportDetailEntity.setAdvertisingId(deserialize.get("advertising_id").toString());
        userAppsflyerReportDetailEntity.setOsVersion(deserialize.get("os_version").toString());
        userAppsflyerReportDetailEntity.setPlatform(deserialize.get("platform").toString());
        System.err.println(111);
    }

    private String getUtcTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf.format(new Date());

    }


    /**
     * 异步推送数据到appsFlyer
     *
     * @param pushType
     * @param pushData
     */
    @Async
    @Override
    public Response asyncTraceEvent(AppsFlyerEventDefType pushType, Map<String, Object> pushData) {
        final String userCode = (String) pushData.get("userCode");
        String appCode = AppCodeEnum.MEBOO.getAppCode();
        if (isTestEnv) {
            logger.info("asyncTraceEventNotExecuteInTestEnv");
            return Response.ok();
        }

        // 事件准入控制
        final List<String> eventTypes = Splitter.on(",").splitToList(pushSwitch);
        final boolean enablePushFlag = AppsFlyerEventDefType.enablePushDataSwitch(eventTypes, pushType);
        if (!enablePushFlag) {
            logger.info("enablePushSwitch:{}, pushType:{}", pushSwitch, pushType.getEventCode());
            return Response.ok();
        }


        JSONObject req = new JSONObject();
        String url = "https://api2.appsflyer.com/inappevent/";
        try {
            logger.info("PushDataToAppsFlyerBegin, pushType:{}, pushData:{}", pushType.getEventCode(), JSONObject.toJSONString(pushData));

            UserAppflyersMappingEntity userAppflyersMappingEntity = userAppflyersMappingDao.getUserAppflyersMappingEntities(userCode);
            if (Objects.isNull(userAppflyersMappingEntity)) {
                logger.error("AppsFlyersUidNotExists, pushType:{}, pushData:{}", pushType.getEventCode(), JsonUtil.toJson(pushData));
                return Response.ok();
            }

            String params = "";
            JSONObject eventContent = new JSONObject();
            req.put("eventName", pushType.getEventCode());
            req.put("eventTime", getUtcTime());
            if (pushData.containsKey("orderNo")) {
                req.put("orderNo", pushData.get("orderNo"));
            }
            if (pushData.containsKey("uid")) {
                req.put("uid", pushData.get("uid"));
            }
            if (pushData.containsKey("appCode") && pushData.get("appCode") != null) {
                appCode = (String) pushData.get("appCode");
            }

            req.put("appsflyer_id", userAppflyersMappingEntity.getAppflyersId());
            try {
                UserAppsflyerReportDetailEntity userAppsflyerReportDetailEntity = userAppsflyerReportDetailDao.selectLatestByAfId(userAppflyersMappingEntity.getAppflyersId());
                if (userAppsflyerReportDetailEntity != null) {
                    req.put("advertising_id", userAppsflyerReportDetailEntity.getAdvertisingId());
                }
            } catch (Exception e) {
                logger.error("asyncTraceEvent advertising_id get error , afId:{},", userAppflyersMappingEntity.getAppflyersId(), e);
            }
            req.put("customer_user_id", userCode);
            if (EventPushType.PushDataAndIncome.equals(pushType.getType())) {
                eventContent.put(pushType.getValue(), pushData.get("amount"));
                eventContent.put("af_revenue", pushData.get("amount"));
                eventContent.put("af_currency", "USD");
                eventContent.put("af_content_type", pushData.get("googlepay"));
                eventContent.put("af_content_id", pushData.get("productCode"));
                req.put("eventCurrency", "USD");
                params += "monetary=" + pushData.get("amount") + "&content_id=" + pushData.get("productCode");
            } else {
                eventContent.put(pushType.getValue(), 1);
                params += "monetary=N/A&content_id=N/A";
            }
            req.put("eventValue", eventContent);
//            Map<String, String> header = Maps.newConcurrentMap();
//            header.put("accept", "application/json");
//            header.put("content-type", "application/json");
//            header.put("authentication", auth);
            url = url + getAppPackageName(appCode) + "?" + params;
            logger.info("PushDataToAppsFlyerSuccess, body:{}", req.toJSONString());
            if (isReview) {
                userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.PUSH_DATA_TO_APPSFLYER_V2, TaskStatusEnum.REVIEW, req.toJSONString(), "Review", pushType.getEventCode(), url, appCode);
            } else {
                userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.PUSH_DATA_TO_APPSFLYER_V2, TaskStatusEnum.INIT, req.toJSONString(), "Waiting", pushType.getEventCode(), url, appCode);
            }

            // 增加firebase数据推送，目前仅支持PP
            addTaskForFirebase(appCode, pushType, req);

        } catch (Exception e) {
            userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.PUSH_DATA_TO_APPSFLYER_V2, TaskStatusEnum.FAILED, req.toJSONString(), "Failed", pushType.getEventCode(), url, appCode);
            logger.error("PushDataToAppsFlyerFailed, pushType:{}, pushData:{}", pushType.getEventCode(), JSONObject.toJSONString(pushData), e);

            // 增加firebase数据推送，目前仅支持PP
            addFailedTaskForFirebase(appCode, pushType, req);
        }
        return Response.ok();
    }

    private void addFailedTaskForFirebase(String appCode, AppsFlyerEventDefType pushType, JSONObject req) {
        if (!AppCodeEnum.PP.getAppCode().equals(appCode)) {
            return;
        }
        String url = nacosValueConfig.ppFirebaseEventTrackingUrl();
        userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.PUSH_DATA_TO_FIREBASE_V1, TaskStatusEnum.FAILED, req.toJSONString(), "Failed", pushType.getEventCode(), url, appCode);
        logger.error("============添加Firebase推送任务失败, pushType:{}, req:{}", pushType.getEventCode(), JSONObject.toJSONString(req));
    }

    private void addTaskForFirebase(String appCode, AppsFlyerEventDefType pushType, JSONObject req) {
        if (!AppCodeEnum.PP.getAppCode().equals(appCode)) {
            return;
        }
        String url = nacosValueConfig.ppFirebaseEventTrackingUrl();
        if (isReview) {
            userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.PUSH_DATA_TO_FIREBASE_V1, TaskStatusEnum.REVIEW, req.toJSONString(), "Review", pushType.getEventCode(), url, appCode);
        } else {
            userTaskDetailDao.addHasExecutedTask(TaskTypeEnum.PUSH_DATA_TO_FIREBASE_V1, TaskStatusEnum.INIT, req.toJSONString(), "Waiting", pushType.getEventCode(), url, appCode);
        }
        logger.info("============添加Firebase推送任务成功, pushType:{}, req:{}", pushType.getEventCode(), JSONObject.toJSONString(req));
    }

    private String getAppPackageName(String appCode) {
        String appPackageName = appId;
        if (appCode.equals(AppCodeEnum.PP.getAppCode())) {
            appPackageName = ppId;
        }
        return appPackageName;
    }


    @Override
    public Response<Boolean> fetNewAccountFlag(String userCode) {
        final UserEntity userEntity = userDao.selectByUserCode(userCode);
        if (Objects.isNull(userEntity) || Objects.isNull(userEntity.getGmtCreate())) {
            return Response.ok(Boolean.FALSE);
        }
        String createAccountDate = DateUtil.format(userEntity.getGmtCreate(), DatePattern.PURE_DATE_PATTERN);
        final boolean isNewAccount = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN).equalsIgnoreCase(createAccountDate);
        return Response.ok(isNewAccount);
    }


    /**
     * 存储appFlyers用户与系统用户映射关系
     */
    @Override
    public synchronized Response queryOrStoreIfNotExists(StoreAppsflyerUserMappingReq request) {
        logger.info("queryOrStoreIfNotExists1, request:{}", JSONObject.toJSONString(request));

        if (Objects.isNull(request)) {
            return Response.ok();
        }

        // 记录客户端上报的信息
        final UserEntity currentUser = userDao.selectByUserCode(request.getUserCode());
        addAppsflyerInfo(request, currentUser);

        final List<UserAppflyersMappingEntity> entitiesByUserCode = getUserAppflyersByUserCode(request.getUserCode());
        if (CollectionUtils.isNotEmpty(entitiesByUserCode)) {
            return Response.ok(userAppsflyerMappingMapper.toDto(entitiesByUserCode.get(0)));
        }

        final List<UserAppflyersMappingEntity> existsRecordWithNoUserCode = userAppflyersMappingDao.getAppflyerWithoutUsercode(request.getAppflyersId());
        if (CollectionUtils.isEmpty(existsRecordWithNoUserCode)) {
            UserAppflyersMappingEntity newRecord = storeAppflyerInfo(request);
            return Response.ok(userAppsflyerMappingMapper.toDto(newRecord));
        }

        // 存在记录但与user无关联关系
        // 查找当前用户的邮箱或手机号码对应的最早appflyerId信息
        if (currentUser == null) {
            return Response.error("currentUserNotExists");
        }




        // 设置关联关系
        setUserCodeForExistsRecord(request, existsRecordWithNoUserCode.get(0));
        // 更新user表中的afid字段，并推送注册信息到appflyers
        setAfidAndPushData(request);
        return Response.ok(userAppsflyerMappingMapper.toDto(existsRecordWithNoUserCode.get(0)));
    }

    private void addAppsflyerInfo(StoreAppsflyerUserMappingReq request, UserEntity currentUser) {
        try {
            final String content = request.getContent();
            if (StringUtils.isEmpty(content)) {
                return;
            }
            final JSONObject contentJson = JSONObject.parseObject(content);
            if (contentJson != null && contentJson.containsKey("af_status")) {
                // 获取流量来源
                String from = StringUtils.isEmpty(contentJson.getString("af_status")) ? "Organic" : contentJson.getString("af_status");

                // 更新自然人中的流量来源
                Integer trafficType = from.equalsIgnoreCase("Organic") ? TrafficSourceEnum.Organic.getType() : TrafficSourceEnum.None_Organic.getType();
                if (currentUser != null) {
                    addCustomer(trafficType, null, currentUser);
                }

                // 保存客户端上传信息
                UserAppsflyerFromAppEntity existsRecord = userAppsflyerFromAppDao.getAppsflyerFromInfo(request.getUserCode(), request.getAppflyersId());
                if (existsRecord != null) {
                    return;
                }

                // 获取流量来源：自然流量需要进一步获取渠道信息，渠道不为空，为非自然流量
                if (from.equalsIgnoreCase("Organic")) {
                    final UserAppsflyerReportDetailEntity afDetail = userAppsflyerReportDetailDao.selectLatestByAfId(request.getAppflyersId());
                    if (afDetail != null && (StringUtils.isNotEmpty(afDetail.getMediaSource()) || StringUtils.isNotEmpty(afDetail.getAfChannel()))) {
                        from = "Non-organic";
                    }
                }

                userAppsflyerFromAppDao.addAppsflyerFromInfo(request.getUserCode(), request.getAppflyersId(), from.equalsIgnoreCase("Non-organic") ? 2 : 1);
                userAppsflyerFromAppDetailDao.addAppsflyerFromInfoDetail(request.getUserCode(), request.getAppflyersId(), content);

            }
        } catch (Exception e) {
            logger.error("===保存af数据异常, request:{}", JSONObject.toJSONString(request), e);
        }
    }

    @Override
    public Response updateAppflyerInfo(StoreAppsflyerUserMappingReq request) {
        if (request == null || StringUtils.isEmpty(request.getAppflyersId()) || StringUtils.isEmpty(request.getChannel())) {
            logger.error("updateAppflyerInfoError, requestIsEmpty, request:{}", JSONObject.toJSONString(request));
            return Response.ok();
        }
        final UserAppflyersMappingEntity existsRecord = userAppflyersMappingDao.getAppflyerByAfid(request.getAppflyersId());
        if (existsRecord == null) {
            UserAppflyersMappingEntity newRecord = new UserAppflyersMappingEntity();
            newRecord.setAppflyersId(request.getAppflyersId());
            newRecord.setChannel(request.getChannel());
            newRecord.setContent(request.getContent());
            newRecord.setCampaign(request.getCampaign());
            newRecord.setAfAdset(request.getAfAdset());
            newRecord.setAfAd(request.getAfAd());
            userAppflyersMappingDao.insert(newRecord);
            return Response.ok();
        }

        if (StringUtils.isEmpty(existsRecord.getChannel())|| "l1".equals(existsRecord.getChannel())) {
            existsRecord.setChannel(request.getChannel());
            existsRecord.setContent(request.getContent());
            existsRecord.setCampaign(request.getCampaign());
            existsRecord.setAfAdset(request.getAfAdset());
            existsRecord.setAfAd(request.getAfAd());
            userAppflyersMappingDao.updateByPrimaryKey(existsRecord);
            // 更新channel
            userDao.updateChannel(request.getAppflyersId(), request.getChannel());
            return Response.ok();
        }

        return null;
    }

    private void setUserCodeForExistsRecord(StoreAppsflyerUserMappingReq request, UserAppflyersMappingEntity existsRecordWithNoUserCode) {
        existsRecordWithNoUserCode.setUserCode(request.getUserCode());
        existsRecordWithNoUserCode.setDataCompleteFlag(0);
        if (StringUtils.isNotEmpty(request.getChannel())) {
            existsRecordWithNoUserCode.setAppflyersId(request.getAppflyersId());
            existsRecordWithNoUserCode.setChannel(request.getChannel());
            existsRecordWithNoUserCode.setAppflyersIdCurrent(request.getCurrentAppflyersId());
            existsRecordWithNoUserCode.setChannelCurrent(request.getCurrentChannel());
            existsRecordWithNoUserCode.setContent(request.getContent());
            existsRecordWithNoUserCode.setCampaign(request.getCampaign());
            existsRecordWithNoUserCode.setAfAdset(request.getAfAdset());
            existsRecordWithNoUserCode.setAfAd(request.getAfAd());
            if (!request.getChannel().equals("l1")) {
                existsRecordWithNoUserCode.setDataCompleteFlag(1);
            }
        }
        userAppflyersMappingDao.updateByPrimaryKey(existsRecordWithNoUserCode);
    }


    private UserAppflyersMappingEntity storeAppflyerInfo(StoreAppsflyerUserMappingReq req) {

        UserAppflyersMappingEntity entity = new UserAppflyersMappingEntity();
        entity.setUserCode(req.getUserCode());
        entity.setAppflyersId(req.getAppflyersId());
        entity.setChannel(req.getChannel());
        entity.setContent(req.getContent());
        entity.setLaunchTime(req.getLaunchTime());
        entity.setCampaign(req.getCampaign());
        entity.setAfAdset(req.getAfAdset());
        entity.setAfAd(req.getAfAd());
        entity.setDataCompleteFlag(0);
        if (StringUtils.isNotEmpty(req.getChannel()) && !req.getChannel().equals("l1")) {
            entity.setDataCompleteFlag(1);
        }
        userAppflyersMappingDao.insert(entity);

        if (StringUtils.isNotEmpty(req.getUserCode())) {
            setAfidAndPushData(req);
        }

        return entity;
    }

    private void setAfidAndPushData(StoreAppsflyerUserMappingReq StoreAppsflyerUserMappingReq) {
        final UserEntity userEntity = userDao.selectByUserCode(StoreAppsflyerUserMappingReq.getUserCode());
        userEntity.setChannel(StoreAppsflyerUserMappingReq.getChannel());
        userEntity.setAppsFlyerUid(StoreAppsflyerUserMappingReq.getAppflyersId());
//        userEntity.setRegisterDate(new Date());
        userDao.updateByPrimaryKey(userEntity);

        // 推送注册数据到appsFlyer
//        final HashMap<String, Object> pushData = Maps.newHashMap();
//        pushData.put("userCode", StoreAppsflyerUserMappingReq.getUserCode());
//        asyncTraceEvent(AppsFlyerEventDefType.Registration, pushData);
    }


    private List<UserAppflyersMappingEntity> getUserAppflyersByUserCode(String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            return Lists.newArrayList();
        }
        final HashMap<String, Object> params = Maps.newHashMap();
        params.put("userCode", userCode);
        return userAppflyersMappingDao.selectByParams(params);
    }

    private List<UserAppflyersMappingEntity> getUserAppflyersByUID(String appsFlyerUID) {
        if (StringUtils.isEmpty(appsFlyerUID)) {
            return Lists.newArrayList();
        }
        final HashMap<String, Object> params = Maps.newHashMap();
        params.put("appflyersId", appsFlyerUID);
        return userAppflyersMappingDao.selectByParams(params);
    }

}
